package com.cn.wanxi.servlet;

import com.alibaba.fastjson.JSONObject;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.IUserService;
import com.cn.wanxi.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        /**
         * 1.乱码
         *   1.1 得到页面的数据
         *    1.2 封装页面数据
         * 2.调用服务逻辑层
         * 3.得到数据
         * 4.返回结果
         */

        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String sex = req.getParameter("sex");
        String code = req.getParameter("code");
        String birthday = req.getParameter("birthday");
        String height = req.getParameter("height");
        String email = req.getParameter("email");
        String hobby = req.getParameter("hobby");
        UserModel userModel = new UserModel();
        userModel.setUsername(username);
        userModel.setPassword(password);
        userModel.setCode(code);
        userModel.setSex(sex);
        userModel.setBirthday(birthday);
        userModel.setEmail(email);
        userModel.setHeight(height);
        userModel.setHobby(hobby);


        IUserService iUserService = new UserServiceImpl();
        String result = iUserService.register(userModel);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", result);
        resp.getWriter().println(jsonObject);
//        req.setAttribute("result", result);
//        req.getRequestDispatcher("/html/register.jsp").forward(req, resp);

    }

    /**
     * 1.分析项目需求
     * 2.用例图，逻辑图
     * 3.创建项目，写前端页面
     * 4.正则表达式   form表单
     * 5.action 连接后台servlet地址  method方法和doget或者dopost的方法一致
     * 5.后台逻辑关系
     *  servlet
     *      1.乱码处理
     *      2.得到页面的值
     *      3.封装到model类
     *      4.调用服务逻辑层
     *      5.得到数据
     *      6.返回页面
     *  service    接口  实现层
     *      1.调用数据实现层dao
     *      2.（判断当前用户名是否存在，如果存在则提示用户不能注册，否则直接注册）
     *      3.返回注册结果
     *  dao   接口  实现层
     *      1.封装sql语句
     *      2.调用JDBC的更新语句
     *   JDBC
     *      1.注册驱动（com.mysql.cj.jdbc.Driver）
     *      2.得到链接 url,username,password
     *      3.编译sql语句
     *      4.执行sql语句
     *      5.返回执行结果
     *      6.关闭连接
     */
}
